//
//  TempModels.swift
//  ANOA
//
//  Created by 邱仙凯 on 2022/10/24.
//  Copyright © 2025 aowang. All rights reserved.
//

import UIKit
import ObjectMapper

public struct TemplateModel: Mappable {
    var detailTitleGramar = "" // 细表小标题语法
    var setDetailCombine = false //
    var field_annotation: String? // 中文名称
    var field_nm: String? // 数据库字段
    var placeholder: String?
    private var field_grammar:String?
    var grmmarArr = [String]()

    var mapCoordinate = [String]()
    var conditionColor = [(String,String)]()//  (条件:颜色)
    var value:String?
    /// 主表  1 细表  2  查询  3
    var placeFlag:String?
    
    
    var isFormSHow:String?  // 表单显示 0 否  1 是     2 仅新增显示    3  仅修改/查看显示 （接口返回）
    var isFilterShow:String? // (筛选的显示逻辑 isFormSHow 为显示 且 不等于page  size)

    
    var is_required:String?  // 必填 0  1
    var isEditEnable:String? // 可编辑 0 否  1 是     2 仅新增可编辑
    var is_multichoice:String? // 多选
    var isSHowList:String?// 列表显示
    var default_value:String? // 默认值
    var field_type:String? // 过滤类型
    
    var ymkD_idNameFlag:String? // id   name

    
    var field_height:String?
    var field_colour:String?
    //  日期    日期时间
    var date_default_value:String? // 1:当天,2:当月第一天;3:前30天;4:前60天;5:前90天,6:后7天，7：前一年
    var date_time_default_value:String? // 1:当前时间,2:当月第一天零点;3:前两个小时
    
    var month_default_value:String? // 月份提前量
    private var lov_url:String? // lov路径
    var pathHandler:PathHandler!
 
     private var lov_field:String? // lov显示字段
    var lovShowArr = [String]()
    var lovLDShowArr = [String]()
    private var lov_field_backfill:String?  // lov回填字段
    var lovBackFillArr = [String]()// 普通回填，支持，和；分割
    var lovLDBackFillArr = [String]() // 联动专用的回填字段
    var lov_scan_url:String? // lov路径
    var computed_expression:String? // 计算表达式
    var zone:String? // 分区名称
    var select_data:String? {
        didSet {
            dealLocalSelectData()
        }
    }// 下拉数据源
   
    var select_field_backfill:String?  {
        didSet {
            dealLocalSelectBack()
        }
    } // 下来数据回填  限制支持2个字段
    var selectDataArr = [SegmenttData]()
    var selectDataBack:LocalSelectDataBack?
    var detail_nm:String?
    var call_port_url:String? // lov回填后再调用接口
    private var port_url_backfill:String? // lov回填后再调用接口  的回填
    var callInterfaceBackArr = [String]()// 调用接口的回填，支持，和；分割
    var upload_type:String?
    var upload_num_max:String?
    var upload_num_min:String?
    var is_upload_back:String?
    var table_source:String?
    var table_nm:String?
    var column_nm:String?
    var upload_fields:String?
    var upload_file_type:String?// 图片位置标识
    var watermark_type:String? // 配置  水印  套餐 由服务端打水印， （客户端水印会篡改时间，不安全）
    var effectArr = [TempEffectDet]()
    var data = [[String:Any]]()
    
    // 单个高度存储
    var oneHeight:CGFloat = 0
    
    public init?(map: Map) {
        
    }
    mutating func setLovUrl(str:String?) {
        self.lov_url = str
 
        let pathArrs = url2PathOriParam(self.lov_url.unwrap)
        self.pathHandler = pathArrs
     
    }
    mutating func setLovField(str:String?) {
        self.lov_field = str
 
        let lovfield = self.lov_field.unwrap.removeAllSapce.removeLineFeed
     
        if lovfield.contains(",") {
            self.lovShowArr = lovfield.components(separatedBy: ",").filter{$0 != ""}
        } else {
            self.lovShowArr = lovfield.components(separatedBy: ";").filter{$0 != ""}
        }
        
        
        
        self.lovLDShowArr = lovfield.components(separatedBy: ";").filter{$0 != ""}

        
    }
    mutating func setLovBackFill(str:String?) {
        self.lov_field_backfill = str
        if self.lov_field_backfill != "" {
            let lovBackfill = self.lov_field_backfill.unwrap.removeAllSapce.removeLineFeed
            if lovBackfill.contains(",") {
                self.lovBackFillArr = lovBackfill.components(separatedBy: ",").filter{$0 != ""}
            } else {
                self.lovBackFillArr = lovBackfill.components(separatedBy: ";").filter{$0 != ""}
            }
             
            // .filter{$0 != ""} 联动的回填不要去空，空有占位作用，标识着第几个
            self.lovLDBackFillArr = lovBackfill.components(separatedBy: ";")

            let valiA = self.lovBackFillArr.filter{$0.contains(":")}
            if valiA.count != self.lovBackFillArr.count  {
                KSToast("\(self.field_nm.unwrap),lov回填字段配置有误")
            }
        }
        
  
    }
    
    mutating func setCallInterfaceBack(str:String?) {
        self.port_url_backfill = str
        
        let lovBackfill = self.port_url_backfill.unwrap.removeAllSapce.removeLineFeed
        if lovBackfill.contains(",") {
            self.callInterfaceBackArr = lovBackfill.components(separatedBy: ",").filter{$0 != ""}
        } else {
            self.callInterfaceBackArr = lovBackfill.components(separatedBy: ";").filter{$0 != ""}
        }
     }
    
    // 整理下拉选数据源
    mutating func dealLocalSelectData() {
        if self.field_type.unwrap == TemplateType.localSelect.rawValue ||
            self.field_type.unwrap == TemplateType.slidingblock.rawValue {
            let arr = self.select_data.unwrap.components(separatedBy: ",")
     
            self.selectDataArr.removeAll()
            for yy in 0..<arr.count {
                let pre = arr[yy].preChar(char: ":").unwrap
                let suf = arr[yy].sufChar(char: ":").unwrap
                self.selectDataArr.append(SegmenttData(id: pre,nm: suf))
            }
         
        }
       
     }
    mutating func dealLocalSelectBack() {
        if self.field_type.unwrap == TemplateType.localSelect.rawValue ||
            self.field_type.unwrap == TemplateType.slidingblock.rawValue {
          
            
            let backarr = self.select_field_backfill.unwrap.removeAllSapce.components(separatedBy: ",")
            guard backarr.count == 2 else {
                KSToast("位置\(self.placeFlag.unwrap)\n--字段\(self.field_nm.unwrap)\n--名称\(self.field_annotation.unwrap)--格式出错\n\(self.select_field_backfill.unwrap)\n回填字段强制为两个字段，用逗号隔开")
                return
            }
            
            //一般都是回填自己，但是配置人员会  加  a.那些
            var idB = backarr[0]
            if idB.contains(".") {
                idB = idB.sufChar(char: ".").unwrap
            }
            var nmB = backarr[1]
            if nmB.contains(".") {
                nmB = nmB.sufChar(char: ".").unwrap
            }
            
            self.selectDataBack = LocalSelectDataBack(idBack: idB,nmBack: nmB)
        }
       
     }
    
    // Mappable
    public mutating func mapping(map: Map) {
        zone <- map[TempSerialKeys.zone]
        field_annotation <- map[TempSerialKeys.field_annotation]
        field_nm <- map[TempSerialKeys.field_nm]
        field_colour <- map[TempSerialKeys.field_colour]
        field_grammar <- map[TempSerialKeys.field_grammar]
        let exp = field_grammar.unwrap
        grmmarArr = getParammerArr(exp)
        
        field_height <- (map[TempSerialKeys.field_height],StringTransform())
        placeFlag <- (map[TempSerialKeys.place_flag],StringTransform())
        is_required <- (map[TempSerialKeys.is_required],StringTransform())
        isEditEnable <- (map[TempSerialKeys.is_enable],StringTransform())
        isFormSHow <- (map[TempSerialKeys.is_show],StringTransform())
        
        is_multichoice <- (map[TempSerialKeys.is_multichoice],StringTransform())
        watermark_type <- (map[TempSerialKeys.watermark_type],StringTransform())

        
        isSHowList <- (map[TempSerialKeys.is_show_list],StringTransform())
        date_default_value <- (map[TempSerialKeys.date_default_value],StringTransform())
        date_time_default_value <- (map[TempSerialKeys.date_time_default_value],StringTransform())
        
        month_default_value <- (map[TempSerialKeys.month_default_value],StringTransform())
        
        placeholder <- map[TempSerialKeys.tooltip]
        
        
        
       if  isFormSHow == "1"
             &&  field_nm != "page"
             &&  field_nm != "size"
        {
            isFilterShow = "1"
        } else {
            isFilterShow = "0"
        }
        
        data <- map[TempSerialKeys.data]
        value <- map[TempSerialKeys.value]
        default_value <- map[TempSerialKeys.default_value]
        field_type <- map[TempSerialKeys.field_type]
        upload_fields <- map[TempSerialKeys.upload_fields]

        
        lov_url <- map[TempSerialKeys.lov_url]
        setLovUrl(str: lov_url)
        lov_field <- map[TempSerialKeys.lov_field]
        setLovField(str: lov_field)
        
        lov_scan_url <- map[TempSerialKeys.lov_scan_url]
        
         
        lov_field_backfill <- map[TempSerialKeys.lov_field_backfill]
        setLovBackFill(str: lov_field_backfill)
        
        
        computed_expression <- map[TempSerialKeys.computed_expression]
        select_data <- map[TempSerialKeys.select_data]
        select_field_backfill <- map[TempSerialKeys.select_field_backfill]
        effectArr <- map[TempSerialKeys.details]
        // 特殊处理，把空的影响字段过滤
        effectArr = effectArr.filter { $0.grammarArr.count > 0 }
        
        detail_nm <- map[TempSerialKeys.detail_nm]
        call_port_url <- map[TempSerialKeys.call_port_url]
        port_url_backfill <- map[TempSerialKeys.port_url_backfill]
        setCallInterfaceBack(str: port_url_backfill)
        
        upload_num_max <- (map[TempSerialKeys.upload_num_max],StringTransform())
        upload_num_min <- (map[TempSerialKeys.upload_num_min],StringTransform())
        
        upload_type <- map[TempSerialKeys.upload_type]
        table_source <- map[TempSerialKeys.table_source]
        table_nm <- map[TempSerialKeys.table_nm]
        column_nm <- map[TempSerialKeys.column_nm]
        
        is_upload_back <- (map[TempSerialKeys.is_upload_back],StringTransform())
        upload_file_type <- map[TempSerialKeys.upload_file_type]
        
        
        let seArr = grmmarArr.filter{ $0.contains(GrammarType.setDetailTitle.rawValue) }
        if seArr.count > 0 {
            let ss = seArr.first!.replacingOccurrences(of: "setDetailTitle@{", with: "").dropLast()
            detailTitleGramar = String(ss)
        }
        
        let cmArr = grmmarArr.filter{ $0.contains(GrammarType.setDetailCombine.rawValue) }
        if cmArr.count > 0 {
            setDetailCombine = true
        }
        
        let ccArr = grmmarArr.filter{ $0.contains(GrammarType.setConditionalColor.rawValue) }
        for item in ccArr {
     
            let ss = item.replacingOccurrences(of: "setConditionalColor@{", with: "").dropLast()
             let sepA = ss.components(separatedBy: ":")

            guard sepA.count == 2 else {
                KSToast("条件颜色配置出错")
                return
            }
            conditionColor.append((sepA[0],sepA[1]))
             
        }
        
        let mapArr = grmmarArr.filter{ $0.contains(GrammarType.setMapCoordinate.rawValue) }
        if mapArr.count > 0 {
            mapCoordinate = mapArr.first!.replacingOccurrences(of: "setMapCoordinate@", with: "").removeBrackets.components(separatedBy: ":")
             
        }
        
        
        dealLocalSelectData()
        dealLocalSelectBack()
    }
    public func dictionaryRepresentation() -> [String: Any] {
      var dictionary: [String: Any] = [:]
        if let value = watermark_type { dictionary[TempSerialKeys.watermark_type] = value }
        if let value = upload_file_type { dictionary[TempSerialKeys.upload_file_type] = value }
//      if let value = idKey { dictionary[SerializationKeys.idKey] = value }
//      if let value = workPlaceN { dictionary[SerializationKeys.workPlaceN] = value }
//      if let value = sTimeN { dictionary[SerializationKeys.sTimeN] = value }
//      if let value = workContentN { dictionary[SerializationKeys.workContentN] = value }
//      if let value = workTarget { dictionary[SerializationKeys.workTarget] = value }
      return dictionary
    }
    
    
}

struct LocalSelectDataBack {
    var idBack:String?
    var nmBack:String?
}
struct GrammarModel {
    var keyword:String? // 语法关键字
    var contents = [String]() // 内容数组
}

struct TempEffectDet: Mappable {
    
    private var expression: String?
    var grammarArr = [GrammarModel]()
    var field_value:String?
    var condition:String?
    init?(map: Map) {
        
    }
    // Mappable
    mutating func mapping(map: Map) {
        expression <- map[TempSerialKeys.expression]
        field_value <- map[TempSerialKeys.field_value]
        condition <- map[TempSerialKeys.condition]

       let expArr = getParammerArr(expression.unwrap)
        grammarArr.removeAll()
        for xxx in expArr {
            let arrrr = getKeyPara(xxx)
            guard arrrr.count > 0 else {
                return
            }
            let conA = Array(arrrr[1..<arrrr.count])
            let onex = GrammarModel(keyword: arrrr[0], contents: conA)
            grammarArr.append(onex)
        }
        
    }
}

struct MeSuperModel: Mappable {
    var directory_nm:String?
    var tempArr = [MainTempModel]()
    
    init?(map: Map) {
        
    }
    // Mappable
    mutating func mapping(map: Map) {
        directory_nm <- map[TempSerialKeys.directory_nm]
        tempArr <- map[TempSerialKeys.details]
        
    }
}

